package com.qdxwx.data.service.course;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.DateUtils;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.mapper.course.CourseStudyHistoryMapper;
import com.qdxwx.models.course.CourseDTO;
import com.qdxwx.models.course.CourseNode;
import com.qdxwx.models.course.CourseStudyHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * CourseStudyHistory接口
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class CourseStudyHistoryServiceImpl implements CourseStudyHistoryService {

	@Autowired
	private CourseStudyHistoryMapper courseStudyHistoryMapper;
	@Autowired
	private CourseNodeService courseNodeService;

	/**
	 * 添加CourseStudyHistory
	 * 要添加的CourseStudyHistory
	 */
	@Override
	public int insert(CourseStudyHistory courseStudyHistory) {
		courseStudyHistory.setUpdateTime(LocalDateTime.now());
		return courseStudyHistoryMapper.create(courseStudyHistory);
	}

	/**
	 * 添加播放记录和播放次数
	 */
	@Override
	public void playerTimes(CourseStudyHistory courseStudyHistory) {
		// 查询是否添加过记录
		List<CourseStudyHistory> courseStudyHistoryList = getList(courseStudyHistory);
		if (ObjectUtils.isNull(courseStudyHistoryList)) {
			// 如果没有添加过则添加记录
			courseStudyHistory.setDataback(DateUtils.toString("yyyy-MM-dd HH:mm:ss"));
			courseStudyHistory.setPlayerCount(1);
			insert(courseStudyHistory);
		} else {
			// 如果添加过则更新记录
			CourseStudyHistory courseStudy = courseStudyHistoryList.get(0);
			courseStudyHistory.setId(courseStudy.getId());
			// 更新时间记录存字段
			String databack = courseStudy.getDataback();
			if (databack.length() > 380) {
				databack = databack.substring(0, databack.lastIndexOf(","));
			}
			courseStudyHistory.setDataback(DateUtils.toString("yyyy-MM-dd HH:mm:ss") + "," + databack);
			courseStudyHistory.setPlayerCount(courseStudy.getPlayerCount() + 1);
			update(courseStudyHistory);
		}
	}

	/**
	 * 修改CourseStudyHistory
	 * 要修改的CourseStudyHistory
	 */
	@Override
	public void update(CourseStudyHistory courseStudyHistory) {
		courseStudyHistory.setUpdateTime(LocalDateTime.now());
		courseStudyHistoryMapper.update(courseStudyHistory);
	}

	/**
	 * 根据条件获取CourseStudyHistory列表
	 * 查询条件
	 */
	@Override
	public List<CourseStudyHistory> getList(CourseStudyHistory courseStudyHistory) {
		return getList(courseStudyHistory, null);
	}

	@Override
	public List<CourseStudyHistory> getList(CourseStudyHistory courseStudyHistory, PageRequest page) {
		return courseStudyHistoryMapper.selectList(courseStudyHistory, page);
	}

	@Override
	public int count(CourseStudyHistory courseStudyHistory) {
		return courseStudyHistoryMapper.count(courseStudyHistory);
	}


	@Override
	public CourseStudyHistory getLastByUserId(long userId) {
		return courseStudyHistoryMapper.selectLastByUserId(userId, 0);
	}

	@Override
	public CourseStudyHistory getLastByUserId(long userId, int courseId) {
		return courseStudyHistoryMapper.selectLastByUserId(userId, courseId);
	}

	@Override
	public int deleteByIds(String ids) {
		return courseStudyHistoryMapper.deleteByIds(TKConvert.toStrArray(ids));
	}

	//设置是否播放标识
	@Override
	public void setIsStudy(List<CourseNode> nodeTrees, List<CourseStudyHistory> courseStudyHistories) {
		if (courseStudyHistories == null || courseStudyHistories.size() < 1) {
			return;
		}
		if (nodeTrees == null || nodeTrees.size() < 1) {
			return;
		}
		for (CourseNode parentNode : nodeTrees) {
			if (parentNode.getChildren() != null) {
				for (CourseNode node : parentNode.getChildren()) {
					if (courseStudyHistories.stream().filter(study -> study.getNodeId() == node.getNodeId()).count() > 0L) {
						node.setProgress(1);//后面需要设置成百份比
					} else {
						node.setProgress(0);
					}
				}
			} else {
				if (courseStudyHistories.stream().filter(study -> study.getNodeId() == parentNode.getNodeId()).count() > 0L) {
					parentNode.setProgress(1);//后面需要设置成百分比
				} else {
					parentNode.setProgress(0);
				}
			}
		}
	}

	@Override
	public void setIsStudy(List<CourseNode> nodeTrees, long userId, int courseId) {
		if (userId < 1 || courseId < 1) return;
		CourseStudyHistory courseStudyHistory = new CourseStudyHistory();
		courseStudyHistory.setCourseId(courseId);
		courseStudyHistory.setUserId(userId);
		setIsStudy(nodeTrees, getList(courseStudyHistory));
	}

	/*设置学习进度*/
	@Override
	public void setStudyPercent(List<CourseDTO> courseList, long userId) {
		if (userId < 1) return;
		if (courseList != null && courseList.size() > 0) {
			//根据 已学课程章节数  和 课程下所有的视频章节 计算比例
			for (CourseDTO course : courseList) {
				setStudyPercent(course, userId);
			}
		}
	}

	/*给某个课程set学习进度*/
	@Override
	public void setStudyPercent(CourseDTO course, long userId) {
		//课程视频节点的 总数
		int nodeCount = courseNodeService.countVideo(course.getCourseId());
		if (nodeCount <= 0) {
			course.setStudyPercent(0);
			return;
		}
		int studyCount = 0;
		if (!"LIVE".equals(course.getSellType())) {
			//TODO:这里要改成分钟数统计学习进度
			CourseStudyHistory courseStudyHistory = new CourseStudyHistory();
			courseStudyHistory.setUserId(userId);
			courseStudyHistory.setCourseId(course.getCourseId());
			//我的课程学习记录
			studyCount = count(courseStudyHistory);
		} else {
			/*如果是直播查询 未开始的（开始了默认学过）节点数量*/
			CourseNode courseNode = new CourseNode();
			courseNode.setCourseId(course.getCourseId());
			courseNode.setLiveBeginTime(LocalDateTime.now());
			/*未开始的直播节点数量*/
			studyCount = courseNodeService.count(courseNode);
			studyCount = nodeCount - studyCount;
		}
		if (studyCount <= 0) {
			course.setStudyPercent(0);
			return;
		}
		course.setStudyPercent(studyCount * 100 / nodeCount);
		if (course.getStudyPercent() > 100) {
			course.setStudyPercent(100);
		}
	}

	@Override
	public int updateCombine(long userId1, long userId2) {
		if(userId1 < 1 || userId2 < 1){
			throw new RuntimeException("更新学习记录：参数错误");
		}
		return courseStudyHistoryMapper.updateCombine(userId1, userId2);
	}
}